package com.qa.service.impl;

import com.qa.constant.CategoryConstant;
import com.qa.constant.RabbitMqConstant;
import com.qa.dto.CategoryAddDTO;
import com.qa.dto.CategoryUpdateDTO;
import com.qa.entity.Category;
import com.qa.mapper.CategoryMapper;
import com.qa.result.Result;
import com.qa.service.CategoryService;
import com.qa.utils.RedisCache;
import com.qa.utils.UserUtil;
import com.qa.vo.CategoryQueryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.qa.constant.CacheConstant.*;

/**
 * @author 徐
 */
@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 交换机名称
     */
    private static final String EXCHANGE_DIRECT = RabbitMqConstant.DIRECT_EXCHANGE;

    /**
     * 添加分类
     *
     * @param categoryAddDTO 分类实体
     * @return 是否成功
     */
    @Override
    public Result addCategory(CategoryAddDTO categoryAddDTO) {
        // 创建者id
        Long userId = UserUtil.getCurrentUserId();

        Category category = Category.builder()
                .name(categoryAddDTO.getName())
                .open(categoryAddDTO.getOpen())
                // 设置创建者id
                .creator(userId)
                // 状态为存在
                .status(CategoryConstant.STATUS_EXISTENCE)
                .build();

        if (categoryMapper.addCategory(category) <= 0) {
            return Result.error(CategoryConstant.ADD_CATEGORY_FAIL);
        } else {
            // 清除缓存
            redisCache.deleteObjects(CACHE_KEY_PREFIX + CATEGORY + DOUBLE_COLON + userId);
            // log.info("清除缓存成功，共清除" + num + "个缓存");
            return Result.success();
        }
    }

    /**
     * 查询某一用户的所有分类
     *
     * @param userId 用户id
     * @return List<Category>
     */
    @Override
    @Cacheable(value = "category", key = "#userId")
    public List<Category> getCategoryByUser(Long userId) {
        return categoryMapper.getCategoryByUser(userId);
    }

    /**
     * 根据分类名称查询公开的存在的别人的分类（分类id，分类名称，创建者，创建者昵称）
     *
     * @param name 分类名称
     * @return List CategoryQueryVO
     */
    @Override
    public Result<List<CategoryQueryVO>> getCategoryByName(String name) {
        List<CategoryQueryVO> categoryQueryVos = categoryMapper.getCategoryByName(UserUtil.getCurrentUserId(), name);
        return Result.success(categoryQueryVos);
    }

    /**
     * 更新本用户的某一个分类
     *
     * @param categoryUpdateDTO 分类实体
     * @return 是否成功
     */
    @Override
    public Result updateMyCategory(CategoryUpdateDTO categoryUpdateDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryUpdateDTO, category);
        Long userId = UserUtil.getCurrentUserId();
        // 设置创建者id为当前用户
        category.setCreator(userId);
        Integer res = categoryMapper.updateCategory(category);
        if (res < 1) {
            return Result.error(CategoryConstant.UPDATE_CATEGORY_FAIL);
        }
        // 更新成功
        // 清除缓存
        redisCache.deleteObjects(CACHE_KEY_PREFIX + CATEGORY + DOUBLE_COLON + userId);
        return Result.success();
    }

    /**
     * 删除我的分类
     *
     * @param categoryId 分类
     * @return
     */
    @Override
    public Result deleteMyCategory(Long categoryId) {
        Category category = new Category();
        category.setId(categoryId);
        Long userId = UserUtil.getCurrentUserId();
        // 设置创建者id为当前用户
        category.setCreator(userId);
        Integer res = categoryMapper.deleteCategory(category);
        if (res < 1) {
            return Result.error(CategoryConstant.DELETE_CATEGORY_FAIL);
        }
        // 消息-分类id
        String message = category.getId().toString();
        // 发送消息
        rabbitTemplate.convertAndSend(EXCHANGE_DIRECT, RabbitMqConstant.KEY_DELETE_QUESTION_CATEGORY, message);
        // 清除缓存
        redisCache.deleteObjects(CACHE_KEY_PREFIX + CATEGORY + DOUBLE_COLON + userId);
        return Result.success();
    }
}
